/// 联系人列表组件
/// 显示用户联系人列表
library;
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:chat_project/config/theme_config.dart';
import 'package:chat_project/models/user_model.dart';
import 'package:chat_project/providers/user_provider.dart';

class ContactList extends StatefulWidget {
  final Function(User) onContactSelected;
  
  const ContactList({
    super.key,
    required this.onContactSelected,
  });

  @override
  State<ContactList> createState() => _ContactListState();
}

class _ContactListState extends State<ContactList> {
  late TextEditingController _searchController;
  
  @override
  void initState() {
    super.initState();
    _searchController = TextEditingController();
  }
  
  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }
  
  @override
  Widget build(BuildContext context) {
    final userProvider = Provider.of<UserProvider>(context);
    final contacts = userProvider.contacts;
    final isLoading = userProvider.isLoading;
    final error = userProvider.error;
    
    if (isLoading) {
      return const Center(
        child: CircularProgressIndicator(),
      );
    }
    
    if (error != null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(
              Icons.error_outline,
              color: Colors.red,
              size: 48,
            ),
            const SizedBox(height: 16),
            Text(
              '加载失败',
              style: Theme.of(context).textTheme.titleMedium,
            ),
            const SizedBox(height: 8),
            Text(
              error,
              style: Theme.of(context).textTheme.bodyMedium,
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: () => userProvider.loadContacts(),
              child: const Text('重试'),
            ),
          ],
        ),
      );
    }
    
    if (contacts.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.people_outline,
              color: Colors.grey[400],
              size: 64,
            ),
            const SizedBox(height: 16),
            Text(
              '暂无联系人',
              style: Theme.of(context).textTheme.titleMedium?.copyWith(
                    color: Colors.grey[600],
                  ),
            ),
            const SizedBox(height: 8),
            Text(
              '点击右上角的"+"按钮添加联系人',
              style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                    color: Colors.grey[500],
                  ),
            ),
          ],
        ),
      );
    }
    
    // 按字母排序联系人
    final sortedContacts = [...contacts]..sort(
        (a, b) => a.username.toLowerCase().compareTo(b.username.toLowerCase()),
      );
    
    // 按首字母分组
    final Map<String, List<User>> groupedContacts = {};
    
    for (final contact in sortedContacts) {
      final firstLetter = contact.username[0].toUpperCase();
      if (!groupedContacts.containsKey(firstLetter)) {
        groupedContacts[firstLetter] = [];
      }
      groupedContacts[firstLetter]!.add(contact);
    }
    
    // 获取所有分组首字母，并排序
    final List<String> sortedLetters = groupedContacts.keys.toList()..sort();
    
    return Column(
      children: [
        // 搜索框
        Padding(
          padding: const EdgeInsets.all(ThemeConfig.paddingRegular),
          child: TextField(
            controller: _searchController,
            decoration: InputDecoration(
              hintText: '搜索联系人',
              prefixIcon: const Icon(Icons.search),
              suffixIcon: _searchController.text.isNotEmpty
                  ? IconButton(
                      icon: const Icon(Icons.clear),
                      onPressed: () {
                        _searchController.clear();
                        setState(() {});
                      },
                    )
                  : null,
              filled: true,
              fillColor: Colors.grey[100],
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(ThemeConfig.borderRadiusRound),
                borderSide: BorderSide.none,
              ),
              contentPadding: const EdgeInsets.symmetric(
                horizontal: ThemeConfig.paddingRegular,
                vertical: ThemeConfig.paddingSmall,
              ),
            ),
            onChanged: (_) => setState(() {}),
          ),
        ),
        
        // 联系人列表
        Expanded(
          child: ListView.builder(
            itemCount: sortedLetters.length,
            itemBuilder: (context, index) {
              final letter = sortedLetters[index];
              final letterContacts = groupedContacts[letter]!;
              
              // 过滤搜索结果
              final searchQuery = _searchController.text.toLowerCase();
              final filteredContacts = searchQuery.isEmpty
                  ? letterContacts
                  : letterContacts
                      .where((contact) =>
                          contact.username.toLowerCase().contains(searchQuery))
                      .toList();
              
              // 如果过滤后没有联系人，则不显示该分组
              if (filteredContacts.isEmpty) {
                return const SizedBox.shrink();
              }
              
              return Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 分组标题
                  Padding(
                    padding: const EdgeInsets.only(
                      left: ThemeConfig.paddingRegular,
                      top: ThemeConfig.paddingRegular,
                      right: ThemeConfig.paddingRegular,
                      bottom: ThemeConfig.paddingSmall,
                    ),
                    child: Text(
                      letter,
                      style: TextStyle(
                        fontSize: ThemeConfig.fontSizeSmall,
                        fontWeight: FontWeight.bold,
                        color: ThemeConfig.primaryColor,
                        backgroundColor: Colors.grey[200],
                      ),
                    ),
                  ),
                  
                  // 联系人列表项
                  ...filteredContacts.map((contact) => _buildContactItem(contact)),
                ],
              );
            },
          ),
        ),
      ],
    );
  }
  
  // 构建联系人列表项
  Widget _buildContactItem(User contact) {
    return ListTile(
      leading: CircleAvatar(
        radius: 20,
        backgroundColor: ThemeConfig.primaryColor.withOpacity(0.1),
        child: Text(
          contact.username.isNotEmpty 
              ? contact.username.substring(0, 1).toUpperCase() 
              : '?',
          style: const TextStyle(
            fontSize: ThemeConfig.fontSizeMedium,
            fontWeight: FontWeight.bold,
            color: ThemeConfig.primaryColor,
          ),
        ),
      ),
      title: Text(
        contact.username,
        style: const TextStyle(
          fontSize: ThemeConfig.fontSizeMedium,
          fontWeight: FontWeight.bold,
        ),
      ),
      subtitle: contact.bio.isNotEmpty
          ? Text(
              contact.bio,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: const TextStyle(
                fontSize: ThemeConfig.fontSizeSmall,
                color: ThemeConfig.textSecondaryColor,
              ),
            )
          : null,
      trailing: contact.isOnline
          ? Container(
              width: 12,
              height: 12,
              decoration: BoxDecoration(
                color: ThemeConfig.successColor,
                shape: BoxShape.circle,
                border: Border.all(
                  color: Colors.white,
                  width: 2,
                ),
              ),
            )
          : null,
      onTap: () => widget.onContactSelected(contact),
    );
  }
} 